import { login } from '@/api/user'
import { getToken, setToken, removeToken } from '@/utils/auth'
// import { resetRouter } from '@/router'

const getDefaultState = () => {
  return {
    token: getToken() || '',
    userInfo: JSON.parse(localStorage.getItem('userInfo')) || {}
  }
}

const state = getDefaultState()

const mutations = {
  // 登录存储
  setUserInfo(state, data) {
    console.log(data.user)
    state.userInfo = data.user
    localStorage.setItem('userInfo', JSON.stringify(data.user))
  },
  setToken(state, data) {
    setToken(data.jwt)
    state.token = data.jwt
  },

  // 退出登录移除
  removeUserInfo(state) {
    state.userInfo = {}
    localStorage.removeItem('userInfo')
  },
  removeToken(state) {
    state.token = ''
    removeToken()
  }
}

const actions = {
  // 登录
  async login(store, loginForm) {
    const res = await login(loginForm)
    // console.log(res)
    store.commit('setUserInfo', res)
    store.commit('setToken', res)
  },

  // 退出登录
  async logout(store) {
    store.commit('removeUserInfo')
    store.commit('removeToken')
  }

}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}

